import React, { Component } from 'react';
import {Button, Checkbox, Divider, Form, Icon, Input, message, Select, Switch} from 'antd';
import { messages } from "share/common";
import Chooser from "components/chooser";
import PDService from 'containers/enterprise-manage/person-manage/person-detail/person-detail.service';
import ListSelector from "components/list-selector";
const FormItem = Form.Item;
const Option = Select.Option;
import {connect} from 'react-redux';

class NewBankCard extends Component {

  state = {
    loading: false,
    card: {},//当前编辑或新增的银行卡
    cardTypeList: [],//银行卡类型的数组
    showListSelector: false,
  };

  componentDidMount() {
    const { card, cardTypeList } = this.props.params;
    this.setState({ card, cardTypeList })
  }

  //去添加银行卡
  addCard = (e) => {
    e.preventDefault();
    let {card} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (!card.bankCode) {
          //请选择银行名称
          message.warning(messages('common.select')/*请选择*/ + messages('basic-5.key152')/*银行名称*/);
          return;
        }
        Object.assign(card, values);
        // card.bankAccountType = values.bankAccountType;
        if(!card.bankAccountType){
          card.bankAccountTypeName = "";
        }
        this.createUpdateCard(card);
      }
    })
  };
  cancelCard = () => {
    // 在这里重置一下，主要是为了清除模态框之前的状态，
    // 比如有校验字段，当取消再次弹窗的时候，校验提示还会显示出来
    this.props.close();
    this.props.form.resetFields();
  };
  createUpdateCard = (card) => {
    this.setState({
      loading: true,
    });
    card.sourceType = "BANKCARD_ACCOUNT";
    if (card.contactBankAccountOID) {
      PDService.updateBankCard(card)
        .then((res) => {
          this.setState({
            loading: false,
          })
          this.props.close();
        })
        .catch((err) => {
          this.setState({
            loading: false,
          })
        })
    } else {
      PDService.creatBankCard(card)
        .then((res) => {
          //当新增了卡片需要传到父组件，重新刷新组件
          this.setState({
            loading: false,
          })
          this.props.close();
        })
        .catch((err) => {
          this.setState({
            loading: false,
          })
        })
    }

  };

  //监听表单值
  handleFormChange = (e) => {
    if (this.state.loading) {
      this.setState({
        loading: false,
      })
    }
  };

  //银行开户名
  bankAccountNameChange = (e) => {
    let {card} = this.state;
    card.bankAccountName = e.target.value;
    this.setState({
      loading: false,
      card
    })
  }
  //银行账号
  bankAccountNoChange = (e) => {
    let {card} = this.state;
    card.bankAccountNo = e.target.value;
    this.setState({
      loading: false,
      card
    })
  }
  //开户地
  accountLocationChange = (e) => {
    let {card} = this.state;
    let value = e.target.value;
    if(value.length > 100){
      card.accountLocation = value.substring(0,100)
    }else{
      card.accountLocation = value;
    }
    this.setState({
      card
    })
  }
  //状态
  switchCardStatusChange = (e) => {
    let {card} = this.state;
    card.enable = e;
    this.setState({
      loading: false,
      card
    })
  };

  // 是否默认
  handleCardDefaultChange = (e) => {
    let {card} = this.state;
    card.isPrimary = e.target.checked;
    this.setState({
      loading: false,
      card
    })
  };

  //银行
  handleBankCodeChange = (result) => {
    let {card} = this.state;
    if (result.result.length) {
      let e = result.result;
      Object.assign(card,{
        bankCode: e[0].bankCode,
        branchName: e[0].bankBranchName,
        bankName: e[0].bankName,
        bankType: e[0].bankType,
        bankTypeBankCode: e[0].bankType + e[0].bankCode,
        accountLocation: e[0].openAccount
      });
    } else {
      Object.assign(card,{
        bankCode: '',
        branchName: '',
        bankName: '',
        bankType: '',
        bankTypeBankCode: '',
        accountLocation: '',
      });
    }
    this.setState({
      showListSelector: false,
      loading: false,
      card,
    })
  }

  changeListSelector = (e, bool) => {
    this.setState({
      showListSelector: bool,
    });
  };

  render() {
    const { loading, showListSelector } = this.state;
    const { card, cardTypeList } = this.props.params;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span:8 },
      wrapperCol: { span:16 }
    };
    let {company, currentMenuPermission, user} = this.props, currentMenu = currentMenuPermission.currentMenu || {},
      bring = company.employeeNameReal,
      disabled = company.employeeNameReal && company.nameFollowType === 'followedAndUnmodified';
    return (
      <div>
      <Form className="new-form" onChange={this.handleFormChange}>
        {/*状态*/}
        <FormItem {...formItemLayout}
                  label={messages('common.column.status')/*状态*/} colon={true}>
          {getFieldDecorator('enable', {
            initialValue: card.enable,
            valuePropName: 'checked',
          })(
            <Switch/>
          )}
        </FormItem>
        <FormItem {...formItemLayout}
                  label={messages('basic-5.key388')/*设为默认*/}
        >
          {getFieldDecorator('isPrimary', {
            initialValue: card.isPrimary
          })(
            <div>
              <Checkbox defaultChecked={card.isPrimary}
                        checked={card.isPrimary}
                        onChange={this.handleCardDefaultChange}
              >
                {messages('basic-5.key393')/*是（只能有一个默认）*/}
              </Checkbox>
            </div>)}
        </FormItem>
        <div className="standard-divider-title">{messages('basic-5.key176')/*基础信息*/}</div>
        <FormItem  {...formItemLayout} label={messages('basic-5.key394')/*银行卡类型*/}>
          {getFieldDecorator('bankAccountType', {
            initialValue: card.bankAccountType || undefined,
            rules: [{
              required: currentMenu.key !== "person-manage",
              message: messages('basic-5.key2')/*请选择temp*/
            }],
          })(
            <Select placeholder={messages('basic-5.key2')/*请选择temp*/} allowClear>
              {cardTypeList.map(option => {
                return <Option key={option.value}>{option.messageKey}</Option>
              })}
            </Select>
          )}
        </FormItem>
        <FormItem label={
          <span>{messages('basic-5.key152')/*银行名称*/}<span style={{color: 'red'}}>&nbsp;*</span></span>
        }
                  {...formItemLayout}>
          <div style={{width: "66%"}}
               onClick={(e) =>this.changeListSelector(e,true)}
               className="real-input-fake-select">
            <Input placeholder={messages('common.select')/*请选择*/}
                   value={card.branchName}
                   suffix={<Icon type="down" style={{fontSize: 12}}/>}
                   onChange={()=>{}}/>
          </div>
        </FormItem>
        <FormItem {...formItemLayout}
                  label={messages('basic-5.key395')/*银行开户名*/}
        >
          {getFieldDecorator('bankAccountName', {
            initialValue: card.id ? card.bankAccountName : (bring ? (card.presetName || user.fullName) : ""),
            rules: [
              {
                required: true,
                message: messages('common.please.input')/*请输入*/
              },
              {
                max: 100,
                message: messages('basic-5.key396')/*不能超过100个字符*/
              },
              // {
              //   message:messages('basic-5.key397')/*开户名只允许汉字、字母、斜杠、点、括号、空格*/,
              //   validator: (rule, value, cb) => {
              //     if (value === null || value === undefined || value === "") {
              //       cb();
              //       return;
              //     }
              //     // let regExp = /^[a-z\.\u4e00-\u9fa5\\\/]+$/i;
              //     // \u2E80-\uFE4F 汉字包含生僻字
              //     let regExp = /^(?!.*?[\u3000-\u303F\u4DC0-\u4DFF\u2800-\u28FF\u3200-\u32FF\u3300-\u33FF\u2700-\u27BF\u2600-\u26FF\uFE10-\uFE1F\uFE30-\uFE4F])[\u4e00-\u9fbb\u2E80-\uFE4Fa-zA-Z.()（）`·\\\/]+$/i;
              //
              //     //去掉空格
              //     value = value.replace(/ /g, '');
              //     if (value.length <= 100 && regExp.test(value)) {
              //       cb();
              //     } else {
              //       cb(false);
              //     }
              //   },
              // },
            ],
          })(
            <div style={{width: '66%'}}>
              <Input onChange={this.bankAccountNameChange}
                     defaultValue={card.id ? card.bankAccountName : (bring ? (card.presetName || user.fullName) : "")}
                     disabled={disabled}
                     placeholder={messages('common.please.input')/*请输入*/}/>
            </div>
          )}
        </FormItem>
        <FormItem {...formItemLayout}
                  label={messages('basic-5.key208')/*银行卡号*/}
        >
          {getFieldDecorator('bankAccountNo', {
            initialValue: card.bankAccountNo,
            rules: [
              {
                required: true,
                message: messages('common.please.input')/*请输入*/
              },
              //任务编号 9661 银行账号校验必须包含数字
              {
                message: messages('basic-5.key398')/*必须包含数字*/,
                validator: (rule, value, cb) => {
                  if (value === null || value === undefined || value === "") {
                    cb();
                    return;
                  }
                  let regExp = /[0-9]/;
                  //去掉空格
                  value = value.replace(/ /g, '');
                  if (value.length <= 30 && regExp.test(value)) {
                    cb();
                  } else {
                    cb(false);
                  }
                },
              },
              {
                max: 30,
                message: messages('basic-5.key249')/*不能超过30个字符*/
              },
            ],
          })(
            <div style={{width: '66%'}}>
              <Input onChange={this.bankAccountNoChange}
                     defaultValue={card.bankAccountNo}
                     disabled={!!card.id}
                     placeholder={messages('common.please.input')/*请输入*/}/>
            </div>
          )}
        </FormItem>
        <FormItem {...formItemLayout}
                  label={messages('basic-5.key155')/*开户地*/}
        >
          <Input placeholder={messages('common.please.input')/*请输入*/}
                 onChange={this.accountLocationChange}
                 value={card.accountLocation}
          />
        </FormItem>
        <div className="footer-operate" style={{backgroundColor:'#ffffff',left:'0px'}}>
          <Button type="primary" onClick={this.addCard}  loading={loading}>
            {messages('common.save')/*保存*/}
          </Button>
          &nbsp;&nbsp;&nbsp;
          <Button onClick={this.cancelCard}>
            {messages('common.cancel')/*取消*/}
          </Button>
        </div>
      </Form>
        <ListSelector
          visible={showListSelector}
          type="select_bank"
          locale={{emptyText: messages('basic-5.key872')/*当前条件没有搜索到银行，建议分词以提高搜索命中率，例：【工商银行深圳华侨城支行】改为【工商银行 深圳 华侨城支行】*/}}
          selectedData={card.bankCode ? [
            {
              openAccount: card.accountLocation,
              bankBranchName: card.branchName,
              bankCode: card.bankCode,
              bankName: card.bankName,
              bankType: card.bankType,
              bankTypeBankCode: card.bankType + card.bankCode,
            }
          ] : []}
          onOk={this.handleBankCodeChange}
          onCancel={(e) =>this.changeListSelector(e, false)}
          single
        />
      </div>
    )
  }

}
function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission,
    company: state.login.company,
    user: state.login.user,
  }
}
const WrappedNewBankCard = Form.create()(NewBankCard);
export default connect(mapStateToProps)(WrappedNewBankCard);
